import 'dart:convert';

import 'package:douhuaxiangsu/entity/artwork_model.dart';

import '../utils/config_loader/artwork_loader.dart';
import '../utils/db_utils.dart';

/// 作品service
class ArtworkService {
  /// 查询所有作品
  static Future<List<ArtworkModel>> queryAll() async {
    final db = await DbUtils.database;
    return await db.query('artwork', orderBy: 'date_time DESC').then((value) {
      return value.map((e) {
        ArtworkModel a = ArtworkLoader.load(e['data'] as String);
        a.id = e['id'] as int;
        return a;
      }).toList();
    });
  }

  /// 保存作品
  static insert(ArtworkModel artwork) async {
    final db = await DbUtils.database;
    int id = await db.insert('artwork', {
      'data': jsonEncode(artwork.toJson()),
      'date_time': DateTime.now().millisecondsSinceEpoch,
    });
    artwork.id = id;
  }

  /// 更新作品
  static updateById(ArtworkModel artwork) async {
    final db = await DbUtils.database;
    await db.update(
      'artwork',
      {
        'data': jsonEncode(artwork.toJson()),
        'date_time': DateTime.now().millisecondsSinceEpoch,
      },
      where: 'id = ?',
      whereArgs: [artwork.id],
    );
  }

  /// 删除作品
  static delete(int id) async {
    final db = await DbUtils.database;
    await db.delete('artwork', where: 'id = ?', whereArgs: [id]);
  }
}
